﻿using System;
using System.Reflection;
using System.Windows.Forms;

namespace mDaemon
{
    public partial class MainFrom : Form
    {
        private System.Windows.Forms.ContextMenu trayMenu;
        private System.Windows.Forms.Timer _timer;

        public MainFrom()
        {
            InitializeComponent();

            // tray menu
            this.trayMenu = new System.Windows.Forms.ContextMenu();
            var menuStart = new System.Windows.Forms.MenuItem();
            var menuStop = new System.Windows.Forms.MenuItem();
            //var menuOption = new System.Windows.Forms.MenuItem();
            var menuExit = new System.Windows.Forms.MenuItem();
            menuStart.Index = 0;
            menuStart.Text = "Start";
            menuStart.Click += (sender, args) =>
            {
                Daemon.getInstance().start();
            };

            menuStop.Index = 1;
            menuStop.Text = "Stop";
            menuStop.Click += (sender, args) =>
            {
                Daemon.getInstance().stop();
            };

            /*
            menuOption.Index = 1;
            menuOption.Text = "Option";
            menuOption.Click += (sender, args) =>
            {
                // Daemon.getInstance().openBrowser();
            };*/

            menuExit.Index = 1;
            menuExit.Text = "Exit";
            menuExit.Click += (sender, args) =>
            {
                _timer.Stop();
                Daemon.getInstance().exit();
                Application.Exit();
            };

            this.trayMenu.MenuItems.Add(menuStart);
            this.trayMenu.MenuItems.Add(menuStop);
            /*this.trayMenu.MenuItems.Add("-");
            this.trayMenu.MenuItems.Add(menuOption);*/
            this.trayMenu.MenuItems.Add("-");
            this.trayMenu.MenuItems.Add(menuExit);
            
            this.trayIcon.ContextMenu = trayMenu;

            /*
            this.trayIcon.Click += (s, e) =>
            {
                MethodInfo mi = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic);
                mi.Invoke(this.trayIcon, null);
            };
            */

            this.trayIcon.DoubleClick += (s, e) =>
            {
                Daemon.getInstance().openBrowser();
            };
            // timer check to ensure process is running
            _timer = new Timer();
            _timer.Interval = 3000;
            _timer.Tick += (sender, e) => Daemon.getInstance().tick();
            _timer.Start();
        }
        
        protected override void OnLoad(EventArgs e)
        {
            Visible = false;
            ShowInTaskbar = false;
            base.OnLoad(e);
        }
    }
}
